<?php
/**
 * Worker.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/10/24- 4:41 下午
 */
namespace console\components\daemons\cloud;

use common\drivers\queue\Manager;
use console\components\constants\ConsoleConstant;
use Yii;
use yii\helpers\FileHelper;
pcntl_async_signals(TRUE);
class Worker
{


    /**
     * 构造方法
     */
    public function __construct()
    {
        /**
         * 设置work进程名称
         */
        swoole_set_process_name(Yii::$app->params['daemon']['cloud']['workerName']);
    }


    /**
     * work进程执行
     * @throws \yii\base\ExitException
     * @throws \yii\base\InvalidConfigException
     */
    public function run(): void
    {
        while (true)
        {
//            if (memory_get_usage(true) > ConsoleConstant::WORKER_MAX_MEMORY)
//            {
//                Yii::$app->end();
//            }

            $job = $this->process();
            //如没有任务，则休息2秒
            if(!$job)
            {
                sleep(2);
            }
        }
    }


    /**
     * 处理
     * @param array $args
     * @return bool|mixed
     */
    private function process(array $args=[])
    {
        /**
         * 设置阻塞信号
         */
//        pcntl_sigprocmask(SIG_BLOCK, [SIGINT, SIGQUIT, SIGTERM]);

        /**
         * 从redis队列中取任务
         */
        Yii::$app->redis->setex('super_pdd_cloud_work_time_1', 86400, time());
        $this->writeSpiderLog('进程成功得到执行');
        $job = Manager::instance(Yii::$app->params['queue']['cloud'].'_1')->pull();
        $this->writeSpiderLog('成功消费到redis数据');
        if($job) {
            try {
                call_user_func_array([$job, 'handle'], []);
            } catch (\Exception $e) {
                echo $e->getMessage();
            }
        }

        /**
         * 多个进程同时执行消费队列
         */
//        pcntl_sigprocmask(SIG_UNBLOCK, [SIGINT, SIGQUIT, SIGTERM]);

        return $job;
    }

    /**
     * 文件日志记录
     * @param $msg
     * @throws ServicesException
     */
    public function writeSpiderLog($msg)
    {

        $path = Yii::getAlias('@runtime/api/spider_cloud/');

        //目录如果不存就先创建目录
        if(!is_dir($path)) {
            FileHelper::createDirectory($path);
        }

        $cp = fopen($path.'log-'.date('Ymd H:i').'.log', "a+");
        $txt = "【".date('Y-m-d H:i:s',time())."】---".$msg."\r\n";
        fwrite($cp, $txt);
        fclose($cp);

    }
}
